//
//  YZMStockBuyInfoView.m
//  YZMicroStock
//
//  Created by Lv.Dongdong on 16/11/9.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMStockBuyInfoView.h"
#import "YZMConfigureService.h"
#import "NSNumber+Utils.h"
#import "YZClient.h"

@interface YZMStockBuyInfoView () <UITextFieldDelegate>

@property (nonatomic, strong) UILabel *chargePriceLB;
@property (nonatomic, strong) UITextField *amountTF;
@property (nonatomic, strong) UILabel *moneyLB;
@property (nonatomic, strong) YZMConfigureService *service ;
@property (nonatomic, strong) UIView *redPacketView;
@property (nonatomic, strong) UILabel *redPacketLabel;
@property (nonatomic, strong) UIButton *expenseBtn;
@property (nonatomic, strong) UILabel *expenseLabel;


- (void)updateFromData;

@end

@implementation YZMStockBuyInfoView

- (instancetype)init {
    
    if (self = [super init]) {
        
        self.backgroundColor = [YZMAppStyle colorForMain];
        [self createObjects];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateRedpacketView:) name:@"deleteRedPacketView" object:nil];
    }
    
    return self;
}

-(void)updateRedpacketView:(NSNotification *)noti{
    
    self.redPacketView.hidden = YES;
}

- (void)createObjects {
    
    WS(ws)
    
    UIView *buyBgView = [[UIView alloc] init];
    [self addSubview:buyBgView];
    [buyBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.equalTo(ws);
        make.height.mas_equalTo(46);
    }];
    
    UILabel *buyPrice = [YZMAppStyle labelWithMediumWhite];
    buyPrice.text = @"买入价格";
    [buyBgView addSubview:buyPrice];
    [buyPrice mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(buyBgView).offset(15);
        make.centerY.equalTo(buyBgView);
    }];
    
    UILabel *marketPrice = [YZMAppStyle labelWithMediumLightGray];
    marketPrice.text = @"市价委托";
    [buyBgView addSubview:marketPrice];
    [marketPrice mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(buyBgView).offset(-15);
        make.centerY.equalTo(buyBgView);
    }];
    
    UIView *lineView = [YZMAppStyle splitLine];
    [buyBgView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.left.right.equalTo(buyBgView);
    }];
    
    UIView *chargeBgView = [[UIView alloc] init];
    [self addSubview:chargeBgView];
    chargeBgView.tag = 100;
    [chargeBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(buyBgView.mas_bottom);
        make.left.right.height.equalTo(buyBgView);
    }];
    
    UILabel *chargeLB = [YZMAppStyle labelWithMediumWhite];
    chargeLB.text = @"交易综合费";
    [chargeBgView addSubview:chargeLB];
    [chargeLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(chargeBgView).offset(15);
        make.centerY.equalTo(chargeBgView);
    }];
    
    UILabel *yuanLB = [YZMAppStyle labelWithMediumLightGray];
    yuanLB.text = @"元";
    [chargeBgView addSubview:yuanLB];
    [yuanLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(chargeBgView).offset(-15);
        make.centerY.equalTo(chargeBgView);
    }];
    
    self.chargePriceLB = [YZMAppStyle labelWithLargeYellow];
    self.chargePriceLB.text = @"--";
    [chargeBgView addSubview:self.chargePriceLB];
    [self.chargePriceLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(yuanLB.mas_left).offset(-1);
        make.centerY.equalTo(chargeBgView);
    }];
    
    //是否使用红包
    self.redPacketView = [UIView new];
    [self addSubview:self.redPacketView];
    self.redPacketView.hidden = YES;
    self.redPacketView.backgroundColor = [YZMAppStyle appBackgroundColor];
    [self.redPacketView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(55);
        make.left.right.equalTo(self);
        make.top.equalTo(chargeBgView.mas_bottom);
    }];
    
    self.redPacketLabel = [YZMAppStyle labelWithSmallWhite];
    [self.redPacketView addSubview:self.redPacketLabel];
    self.redPacketLabel.text = @"是否使用红包余额（余额：158.00元）";
    [self.redPacketLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.redPacketView).offset(14);
        make.top.equalTo(self.redPacketView).offset(13);
    }];
    
    UILabel *redPacketHintLB = [YZMAppStyle labelWithSmallLightGray];
    redPacketHintLB.text = @"红包余额只能抵扣交易综合费";
    [self.redPacketView addSubview:redPacketHintLB];
    [redPacketHintLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.redPacketLabel.mas_bottom).offset(5);
        make.left.equalTo(self.redPacketLabel);
    }];
    
    self.expenseLabel = [YZMAppStyle labelWithSmallWhite];
    self.expenseLabel.text = @"-158元";
    [self.redPacketView addSubview:self.expenseLabel];
    [self.expenseLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.redPacketLabel.mas_bottom);
        make.right.equalTo(self.redPacketView).offset(-15);;
    }];
    
    self.expenseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.expenseBtn.selected = NO;
    [self.expenseBtn setImage:[UIImage imageNamed:@"icon_redpacket_selected"] forState:UIControlStateNormal];
    [self.expenseBtn setImage:[UIImage imageNamed:@"icon_redpacket_unselected"] forState:UIControlStateSelected];
    [self.expenseBtn addTarget:self action:@selector(selectedExpense:) forControlEvents:UIControlEventTouchUpInside];
    [self.redPacketView addSubview:self.expenseBtn];
    
    [self.expenseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.height.width.mas_equalTo(12);
        make.centerY.equalTo(self.expenseLabel);
        make.right.equalTo(self.expenseLabel.mas_left).offset(-5);
    }];
    
    
    UIView *amountBgView = [[UIView alloc] init];
    [self addSubview:amountBgView];
    amountBgView.tag = 101;
    
    UIView *lineTView = [YZMAppStyle splitLine];
    [chargeBgView addSubview:lineTView];
    [lineTView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.left.right.equalTo(chargeBgView);
    }];
    
    [amountBgView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.equalTo(chargeBgView.mas_bottom);
        make.left.right.height.equalTo(chargeBgView);
    }];
    
    UILabel *buyAmountLB = [YZMAppStyle labelWithMediumWhite];
    buyAmountLB.text = @"买入数量";
    [amountBgView addSubview:buyAmountLB];
    [buyAmountLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(amountBgView).offset(15);
        make.centerY.equalTo(amountBgView);
        make.width.mas_equalTo(65);
    }];
    
    UIButton *plusBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    plusBtn.tag = 1;
    [plusBtn setImage:[UIImage imageNamed:@"icon_count_plus"] forState:UIControlStateNormal];
    [plusBtn setImage:[UIImage imageNamed:@"icon_count_plus_dis"] forState:UIControlStateDisabled];
    [plusBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [amountBgView addSubview:plusBtn];
    [plusBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(amountBgView).offset(-15);
        make.centerY.equalTo(amountBgView);
        make.width.height.mas_equalTo(24);
    }];
    
    UIButton *subBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    subBtn.tag = 2;
    subBtn.enabled = NO;
    [subBtn setImage:[UIImage imageNamed:@"icon_count_sub"] forState:UIControlStateNormal];
    [subBtn setImage:[UIImage imageNamed:@"icon_count_sub_dis"] forState:UIControlStateDisabled];
    [subBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [amountBgView addSubview:subBtn];
    [subBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(buyAmountLB.mas_right).offset(64);
        make.centerY.equalTo(amountBgView);
        make.width.height.mas_equalTo(24);
    }];
    
    self.amountTF = [[UITextField alloc] init];
    self.amountTF.enabled = NO;
    self.amountTF.font = [YZMAppStyle largeSizeFont];
    self.amountTF.textColor = [YZMAppStyle colorForIconColor];
    self.amountTF.text = @"100";
    self.amountTF.textAlignment = NSTextAlignmentCenter;
    self.amountTF.delegate = self;
    self.amountTF.keyboardType = UIKeyboardTypeNumberPad;
    [amountBgView addSubview:self.amountTF];
    [self.amountTF mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(subBtn.mas_right);
        make.right.equalTo(plusBtn.mas_left);
        make.centerY.equalTo(amountBgView);
    }];
    
    UIView *lineThView = [YZMAppStyle splitLine];
    [amountBgView addSubview:lineThView];
    [lineThView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.left.right.equalTo(amountBgView);
    }];
    
    
    UIView *moneyBgView = [[UIView alloc] init];
    moneyBgView.backgroundColor = [YZMAppStyle appBackgroundColor];
    [self addSubview:moneyBgView];
    [moneyBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(amountBgView.mas_bottom);
        make.left.right.height.equalTo(amountBgView);
    }];
    
    UILabel *bottomYuanLb = [YZMAppStyle labelWithMediumLightGray];
    bottomYuanLb.text = @"元";
    [moneyBgView addSubview:bottomYuanLb];
    [bottomYuanLb mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(moneyBgView).offset(-15);
        make.centerY.equalTo(moneyBgView);
    }];
    
    self.moneyLB = [YZMAppStyle labelWithLargeYellow];
    self.moneyLB.text = @"--";
    [moneyBgView addSubview:self.moneyLB];
    [self.moneyLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(bottomYuanLb.mas_left);
        make.centerY.equalTo(bottomYuanLb);
    }];
    
    UILabel *textLB = [YZMAppStyle labelWithMediumLightGray];
    textLB.text = @"资金预计占用";
    [moneyBgView addSubview:textLB];
    [textLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(ws.moneyLB.mas_left);
        make.centerY.equalTo(moneyBgView);
    }];
}

#pragma mark -- event

- (void)clickBtn:(UIButton *)sendr {
    
    UIButton *plusBtn = [self viewWithTag:1];
    UIButton *subBtn = [self viewWithTag:2];
    
    if (!self.schemeModel) {
        
        return;
    }
    
    if (sendr.tag == 1) {
        
        subBtn.enabled = YES;
        double maxAmonut = floor(self.schemeModel.availableMoney / [@(self.realInfo.price * self.service.defaultConfigure.tradingCountRatio).r2fString doubleValue] / 100) * 100;
        
        if (![@(self.service.defaultConfigure.maxStockCount) isEqualGreaterThanDouble:maxAmonut]) {
            
            maxAmonut = self.service.defaultConfigure.maxStockCount;
        }
        NSNumber *currentAmount = @([self.amountTF.text integerValue] + 100);
        
        if (maxAmonut <= 0) {
            
            sendr.enabled = NO;
            return;
        }
        
        if ([currentAmount isEqualGreaterThanDouble:maxAmonut]) {
            
            self.amountTF.text = [NSString stringWithFormat:@"%@", @(maxAmonut).rfString];
            sendr.enabled = NO;
        } else {
            
            self.amountTF.text = [NSString stringWithFormat:@"%@", currentAmount];
        }
    } else {
        
        plusBtn.enabled = YES;
        double minAmonut = 100;
        NSNumber *currentAmount = @([self.amountTF.text integerValue] - 100);
        
        if (![currentAmount isGreaterThanDouble:minAmonut]) {
            
            self.amountTF.text = [NSString stringWithFormat:@"%@", @(minAmonut).rfString];
            sendr.enabled = NO;
        } else {
            
            self.amountTF.text = [NSString stringWithFormat:@"%@", currentAmount];
        }
    }
    
    [self updateFromData];
}

- (void)setSchemeModel:(YZMMyStackModel *)schemeModel {
    
    _schemeModel = schemeModel;
    
    if (self.schemeModel) {
        
        self.amountTF.enabled = YES;
    }
}

//-(void)setInforModel:(YZMRedPacketInfor *)inforModel{
//    
//    if (inforModel) {
//        [self refreshRedPacketInfo:inforModel];
//    }
//}

- (void)selectedExpense:(UIButton *)send {
    
    self.expenseBtn.selected = !self.expenseBtn.isSelected;
    [[NSNotificationCenter defaultCenter]postNotificationName:@"TDUseRedPack" object:nil userInfo:@{@"isuseRedpack":@(!send.selected)}];
}

- (void)updateFromData {
    
    if (self.schemeModel) {
        
        self.amountTF.enabled = YES;
    }
    
    self.service = [YZMTDConfigureService sharedService];
    
    //当前数量
    NSInteger amount = [self.amountTF.text integerValue];
    //点买总金额
    CGFloat currentPrice = [@(self.realInfo.price * self.service.defaultConfigure.tradingCountRatio).r2fString doubleValue];
    
//    double totalMoney = [@(self.realInfo.price * self.service.defaultConfigure.tradingCountRatio).r2fString doubleValue] * amount;
    double totalMoney = currentPrice > self.realInfo.limitUpPrice ? self.realInfo.limitUpPrice * amount : currentPrice * amount;
    
    //交易综合费
    double charge = 0;
    if ([@(totalMoney) isEqualGreaterThanDouble:10000]) {
        
        charge = totalMoney / 10000 * self.service.defaultConfigure.serviceCharge;
    } else {
        
        charge = ceil(totalMoney / 10000) * self.service.defaultConfigure.serviceCharge;
    }
    self.chargePriceLB.text = [NSString stringWithFormat:@"%@", @(charge).r2fString];
    
    //点买金额
    self.moneyLB.text = [NSString stringWithFormat:@"%@", @(totalMoney).r2fString];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"strategyParams" object:self userInfo:@{@"amount":@(amount), @"chargePrice":self.chargePriceLB.text, @"money":self.moneyLB.text}];
    
    [self refreshRedPacketInfo:self.inforModel];
//    [self fetchActivityRedPacketInfor];

}

-(void)setInforModel:(YZMRedPacketInfor *)inforModel{
    
    _inforModel = inforModel;
//    if (inforModel) {
    
        [self refreshRedPacker:inforModel];
//    }
}

-(void)refreshRedPacker:(YZMRedPacketInfor *)infor{
    
    UIView *chargeView = [self viewWithTag:100];
    UIView *amountView = [self viewWithTag:101];
    if ([@(infor.tipBalance) isGreaterThanDouble:0]) {
        self.redPacketView.hidden = NO;
        [amountView mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.top.equalTo(self.redPacketView.mas_bottom);
            make.left.right.height.equalTo(chargeView);
        }];
    
    }else{

        UIView *lineTView = [YZMAppStyle splitLine];
        [chargeView addSubview:lineTView];
        [lineTView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.bottom.left.right.equalTo(chargeView);
        }];
        
        [amountView mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.top.equalTo(chargeView.mas_bottom);
            make.left.right.height.equalTo(chargeView);
        }];
    }
    [self refreshRedPacketInfo:infor];
}

//刷新红包信息
- (void)refreshRedPacketInfo:(YZMRedPacketInfor *)model {
    
    if (model) {
        
        self.redPacketLabel.text = [NSString stringWithFormat:@"是否使用红包余额（余额:%@元）", @(model.tipBalance).r2fString];
        [self refreshExpenseLB:model];
    }
}
- (void)refreshExpenseLB:(YZMRedPacketInfor *)infor {

    if ([@(infor.tipBalance) isEqualGreaterThanDouble:[self.chargePriceLB.text doubleValue]]) {
        
        self.expenseLabel.text = [@"-" stringByAppendingString:self.chargePriceLB.text];
    } else {
        
        self.expenseLabel.text = [NSString stringWithFormat:@"-%@元", @(infor.tipBalance).r2fString];
    }
}

#pragma mark -- UITextFieldDelegate

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    
    UIButton *plusBtn = [self viewWithTag:1];
    UIButton *subBtn = [self viewWithTag:2];
    
    double maxAmonut = floor(self.schemeModel.availableMoney / [@(self.realInfo.price * self.service.defaultConfigure.tradingCountRatio).r2fString doubleValue] / 100) * 100;
    
    if (![@(self.service.defaultConfigure.maxStockCount) isEqualGreaterThanDouble:maxAmonut]) {
        
        maxAmonut = self.service.defaultConfigure.maxStockCount;
    }
    double minAmonut = 100;
    NSNumber *currentAmount = @([textField.text integerValue]);
    
    if (maxAmonut == 0) {
        
        return YES;
    }
    
    if ([currentAmount isGreaterThanDouble: maxAmonut]) {
        
        textField.text = [NSString stringWithFormat:@"%@", @(maxAmonut).p2fString];
        subBtn.enabled = YES;
        plusBtn.enabled = NO;
        [self updateFromData];
        
        return NO;
    } else if (![currentAmount isEqualGreaterThanDouble: minAmonut]) {
        
        textField.text = [NSString stringWithFormat:@"%@", @(minAmonut).r2fString];
        subBtn.enabled = NO;
        plusBtn.enabled = YES;
        [self updateFromData];
        
        return NO;
    } else if ([currentAmount isEqualWithDouble: maxAmonut]) {
        
        subBtn.enabled = YES;
        plusBtn.enabled = NO;
        
    } else if ([currentAmount isEqualWithDouble: minAmonut]) {
        
        subBtn.enabled = NO;
        plusBtn.enabled = YES;
        
    } else {
        
        textField.text = [NSString stringWithFormat:@"%@", @(floor([textField.text integerValue] / 100) * 100)] ;
        subBtn.enabled = YES;
        plusBtn.enabled = YES;
    }
    
    [self updateFromData];
    
    return YES;
}

@end
